//
//  HNSH_TZExchangeViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/6/14.
//

#import "HNSH_TZExchangeViewController.h"

#import "HNSH_TZExchangeTopView.h"
#import "ST_PayPasswordView.h"
#import "ST_TimeDownToors.h"
#import "RXPopMenu.h"

#import "HNSH_TZExchangeRecordViewController.h"

#import "HNSH_ExchangeNetServer.h"

@interface HNSH_TZExchangeViewController ()

/* topView */
@property (nonatomic, strong) HNSH_TZExchangeTopView *topView;

/* leftLabel */
@property (nonatomic, strong) UILabel *leftLabel;
/* rightLabel */
@property (nonatomic, strong) UILabel *rightLabel;

/* countField */
@property (nonatomic, strong) UITextField *countField;

/* 余额 */
@property (nonatomic, strong) UILabel *yeLabel;
/* 可兑换 */
@property (nonatomic, strong) UILabel *kdhLabel;
/* 需消耗购物值 */
@property (nonatomic, strong) UILabel *xhgwzLabel;

/* infoModel */
@property (nonatomic, strong) HNSH_TZExchangeModel *infoModel;

/* codeBgView */
@property (nonatomic, strong) UIView *codeBgView;
/* codeField */
@property (nonatomic, strong) UITextField *codeField;
/* codeButton */
@property (nonatomic, strong) UIButton *codeButton;

@end

@implementation HNSH_TZExchangeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self showNavTitle:@"我的余额" showLeftItem:YES];
        
    [self.view addSubview:self.topView];
    
    [self configBottomView];
    
    [self loadCapitalHdcSwapConfig];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(kScreenWidth-88, kStatusBarHeight, 88, 44);
    [button setTitle:@"兑换记录" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor appBlackLabelColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    button.layer.cornerRadius = 4;
    button.layer.masksToBounds = YES;
    [self.view addSubview:button];
    __weak __typeof(&*self)weakSelf = self;
    [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        HNSH_TZExchangeRecordViewController *vc= [[HNSH_TZExchangeRecordViewController alloc]init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
}

#pragma mark lazy
- (void)loadCapitalHdcSwapConfig {
    [HNSH_ExchangeNetServer requestCapitalHdcSwapConfigSuccess:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            self.infoModel = [HNSH_TZExchangeModel yy_modelWithDictionary:responseObject.resultset];
            self.topView.infoModel = self.infoModel;
            [self.topView configType:self.type infoModel:self.infoModel];
            self.yeLabel.text = [NSString stringWithFormat:@"通证余额：%.2f",[self.infoModel.hdc_balance doubleValue]];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

- (void)loadCapitalHdcSwapApply {
    [HNSH_ExchangeNetServer requestCapitalHdcSwapApplyWithAmount:self.countField.text sms_code:self.codeField.text type:self.type success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self.view makeToast:@"兑换成功"];
            [self loadCapitalHdcSwapConfig];
            self.countField.text = @"";
            self.codeField.text = @"";
            [[ST_TimeDownToors shareTimer] cancelTimer];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

- (void)configBottomView {
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(10, kNavBarAndStatusBarHeight+100, kScreenWidth-20, kScreenHeight-kNavBarAndStatusBarHeight-100)];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    
    //置换按钮
    UIButton *changeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [changeButton setImage:[UIImage imageNamed:@"tz_icon_exchange"] forState:UIControlStateNormal];
    changeButton.frame = CGRectMake(bgView.width/2-15, 40, 30, 30);
    [bgView addSubview:changeButton];
//    __weak __typeof(&*self)weakSelf = self;
//    [[changeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
//        weakSelf.type = weakSelf.type == 2 ? 1 : 2;
//        [weakSelf.topView configType:weakSelf.type infoModel:weakSelf.infoModel];
//        weakSelf.topView.type = weakSelf.type;
//        weakSelf.leftLabel.text = weakSelf.type == 2 ? @"可转赠种子" : @"种子";
//        weakSelf.rightLabel.text = weakSelf.type == 2 ? @"种子" : @"可转赠种子";
//        
//        weakSelf.countField.text = @"";
//        
//        [weakSelf loadTradeReplaceConfig];
//    }];
    
    UILabel *leftDesLabel = [[UILabel alloc]initWithFrame:CGRectMake(changeButton.origin.x-96, changeButton.origin.y, 30, 30)];
    leftDesLabel.text = @"从";
    leftDesLabel.textColor = [UIColor colorWithHexString:@"#999999"];
    leftDesLabel.font = [UIFont systemFontOfSize:16];
    [bgView addSubview:leftDesLabel];
    
    UILabel *leftLabel = [[UILabel alloc]initWithFrame:CGRectMake(changeButton.origin.x-68, changeButton.origin.y, 60, 30)];
    leftLabel.text = @"通证";
    leftLabel.textColor = [UIColor colorWithHexString:@"#333333"];
    leftLabel.font = [UIFont boldSystemFontOfSize:16];
    [bgView addSubview:leftLabel];
    self.leftLabel = leftLabel;
    
    [leftLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(changeButton.mas_centerY);
        make.right.equalTo(changeButton.mas_left).offset(-24);
        make.height.mas_equalTo(22);
    }];
    
    [leftDesLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(leftLabel.mas_centerY);
        make.right.equalTo(leftLabel.mas_left).offset(-12);
        make.height.mas_equalTo(22);
    }];
    
    UILabel *rightDesLabel = [[UILabel alloc]initWithFrame:CGRectMake(changeButton.origin.x+changeButton.width+24, changeButton.origin.y, 30, 30)];
    rightDesLabel.text = @"到";
    rightDesLabel.textColor = [UIColor colorWithHexString:@"#999999"];
    rightDesLabel.font = [UIFont systemFontOfSize:16];
    [bgView addSubview:rightDesLabel];
    
    UILabel *rightLabel = [[UILabel alloc]init];
    rightLabel.text = @"余额";
    rightLabel.textColor = [UIColor colorWithHexString:@"#333333"];
    rightLabel.font = [UIFont boldSystemFontOfSize:16];
    [bgView addSubview:rightLabel];
    self.rightLabel = rightLabel;
    
    [rightLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(changeButton.mas_centerY);
        make.left.equalTo(changeButton.mas_right).offset(53);
        make.height.mas_equalTo(30);
    }];
    WeakSelf(weakSelf);
    rightLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf showChangeAlertWithLabel:rightLabel];
    }];
    [rightLabel addGestureRecognizer:tap];
    
    UIImageView *imgV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"tz_exchang_down"]];
//    imgV.hidden = YES;
    [bgView addSubview:imgV];
//    self.leftDownImgV = imgV;
    [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(changeButton.mas_centerY);
        make.left.equalTo(rightLabel.mas_right).offset(4);
        make.width.height.mas_equalTo(16);
    }];
    
    
    //数量
    UIView *counuBgView = [[UIView alloc]initWithFrame:CGRectMake(32, 90, bgView.width-64, 44)];
    counuBgView.backgroundColor = [UIColor colorWithHexString:@"#F5F5F5"];
    [bgView addSubview:counuBgView];
    counuBgView.layer.cornerRadius = 4;
    counuBgView.layer.masksToBounds = YES;
    
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(12, 0, counuBgView.width-24, counuBgView.height)];
    textField.textColor = [UIColor colorWithHexString:@"#333333"];
    textField.font = [UIFont systemFontOfSize:14];
    textField.placeholder = @"请输入兑换数量";
    textField.keyboardType = UIKeyboardTypeNumberPad;
    NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:textField.placeholder];
    [placeholderString addAttribute:NSForegroundColorAttributeName
                            value:[UIColor colorWithHexString:@"#C8C9CB"]
                            range:NSMakeRange(0, textField.placeholder.length)];
    [placeholderString addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:14]
                            range:NSMakeRange(0, textField.placeholder.length)];
    textField.attributedPlaceholder = placeholderString;
    [counuBgView addSubview:textField];
    self.countField = textField;
    [[textField rac_signalForControlEvents:UIControlEventEditingChanged] subscribeNext:^(__kindof UIControl * _Nullable x) {
        UITextField *field = x;
        [weakSelf loadCapitalHdcSwapCalculation];
//        if (weakSelf.type == 1) {
//            weakSelf.sxfLabel.text = [NSString stringWithFormat:@"手续费：%.2f 种子",[weakSelf.infoModel.poundage_ratio doubleValue] * [field.text integerValue]];
//            weakSelf.maxHdLabel.text = [NSString stringWithFormat:@"置换可获得：%.2f 可转赠种子",(1 - [weakSelf.infoModel.poundage_ratio doubleValue]) * [field.text integerValue]];
//        } else {
//            weakSelf.sxfLabel.text = [NSString stringWithFormat:@""];
//            weakSelf.maxHdLabel.text = [NSString stringWithFormat:@"置换可获得：%.2f 种子", [field.text doubleValue]];
//        }
    }];
    
    //余额
    UILabel *yeLabel = [[UILabel alloc]initWithFrame:CGRectMake(32, counuBgView.origin.y+counuBgView.height+8, bgView.width-64, 17)];
    yeLabel.text = @"通证余额：0.00";
    yeLabel.textColor = [UIColor colorWithHexString:@"#999999"];
    yeLabel.font = [UIFont systemFontOfSize:12];
    [bgView addSubview:yeLabel];
    self.yeLabel = yeLabel;
    
    //可兑换：
    UILabel *kdhLabel = [[UILabel alloc]initWithFrame:CGRectMake(32, yeLabel.origin.y+yeLabel.height+4, bgView.width-64, 17)];
    kdhLabel.text = @"可兑换：0.00现金余额";
    kdhLabel.textColor = [UIColor colorWithHexString:@"#999999"];
    kdhLabel.font = [UIFont systemFontOfSize:12];
    [bgView addSubview:kdhLabel];
    self.kdhLabel = kdhLabel;
    
    //需消耗购物值：
    UILabel *xhgwzLabel = [[UILabel alloc]initWithFrame:CGRectMake(32, kdhLabel.origin.y+kdhLabel.height+4, bgView.width-64, 17)];
    xhgwzLabel.text = @"需消耗购物值：0.00";
    xhgwzLabel.textColor = [UIColor colorWithHexString:@"#999999"];
    xhgwzLabel.font = [UIFont systemFontOfSize:12];
    [bgView addSubview:xhgwzLabel];
    self.xhgwzLabel = xhgwzLabel;
    
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(32, counuBgView.origin.y+counuBgView.height+146, bgView.width-64, 44);
    [button setTitle:@"确认兑换" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    button.backgroundColor = [UIColor appGreenColor];
    button.layer.cornerRadius = 22;
    button.layer.masksToBounds = YES;
    [bgView addSubview:button];
    
    [bgView addSubview:self.codeBgView];
    [self.codeBgView addSubview:self.codeField];
    [bgView addSubview:self.codeButton];
    
    [self.codeBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(32);
        make.right.mas_equalTo(-134);
        make.top.equalTo(counuBgView.mas_bottom).offset(83);
        make.height.mas_equalTo(44);
    }];

    [self.codeField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.right.mas_equalTo(-12);
        make.top.bottom.mas_equalTo(0);
    }];

    [self.codeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-32);
        make.width.mas_equalTo(94);
        make.height.mas_equalTo(44);
        make.centerY.equalTo(self.codeBgView.mas_centerY);
    }];

    [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf loadCapitalHdcSwapApply];
    }];
    
}

- (void)showChangeAlertWithLabel:(UILabel *)label {
    NSArray * showItems = @[[RXPopMenuItem itemTitle:@"余额"],
                            [RXPopMenuItem itemTitle:@"冻结能量"]
    ];
    RXPopMenu * menu = [RXPopMenu menu];
    menu.backColor = [UIColor appWhiteLabelColor];
    menu.titleColor = [UIColor blackColor];
    menu.hideArrow = YES;
    [menu showBy:label withItems:showItems];
    WeakSelf(weakSelf);
    menu.itemActions = ^(RXPopMenuItem *item) {
//        __strong typeof(self) strong = weak;
        label.text = item.title;
        NSLog(@"%@", item.title);
        if ([item.title isEqualToString:@"余额"]) {
            weakSelf.type = 1;
            [self.topView configType:weakSelf.type infoModel:weakSelf.infoModel];
        }
        if ([item.title isEqualToString:@"冻结能量"]) {
            weakSelf.type = 2;
            [self.topView configType:weakSelf.type infoModel:weakSelf.infoModel];
        }
        [weakSelf loadCapitalHdcSwapCalculation];
    };
}

#pragma mark lazy
- (HNSH_TZExchangeTopView *)topView {
    if (!_topView) {
        _topView = [[HNSH_TZExchangeTopView alloc]initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, 100)];
    }
    return _topView;
}

- (UIView *)codeBgView {
    if (!_codeBgView) {
        _codeBgView = [[UIView alloc]init];
        _codeBgView.backgroundColor = [UIColor appBGColor];
        _codeBgView.layer.cornerRadius = 4;
        _codeBgView.layer.masksToBounds = YES;
    }
    return _codeBgView;
}

- (UITextField *)codeField {
    if (!_codeField) {
        _codeField = [[UITextField alloc]init];
        _codeField.textColor = [UIColor appBlackLabelColor];
        _codeField.font = [UIFont boldSystemFontOfSize:14];
        _codeField.placeholder = @"请输入验证码";
        _codeField.keyboardType = UIKeyboardTypeNumberPad;
        NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:_codeField.placeholder];
        [placeholderString addAttribute:NSForegroundColorAttributeName
                                value:[UIColor colorWithHexString:@"#C8C9CB"]
                                range:NSMakeRange(0, _codeField.placeholder.length)];
        [placeholderString addAttribute:NSFontAttributeName
                                value:[UIFont systemFontOfSize:16]
                                range:NSMakeRange(0, _codeField.placeholder.length)];
        _codeField.attributedPlaceholder = placeholderString;
    }
    return _codeField;
}

- (UIButton *)codeButton {
    if (!_codeButton) {
        _codeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_codeButton setTitleColor:[UIColor appGreenColor] forState:UIControlStateNormal];
        _codeButton.titleLabel.font = [UIFont systemFontOfSize:14];
        _codeButton.backgroundColor = [UIColor colorWithHexString:@"#FEEBE9"];
        _codeButton.layer.cornerRadius = 4;
        _codeButton.layer.masksToBounds = YES;
        WeakSelf(weakSelf);
        [[_codeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            UIButton *button = x;
            [weakSelf loadSendCodeWithButton:button];
        }];
    }
    return _codeButton;
}


//发送验证码
- (void)loadSendCodeWithButton:(UIButton *)sendButton {
    [HNSH_UserNetServer requestSendCodeWithUserName:[ST_UserManager shareInstance].user.phone type:KSendCodeType_TongZheng success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [[ST_TimeDownToors shareTimer] startTimerWithTime:60 complate:^(NSInteger time) {
                NSString *timeStr = [NSString stringWithFormat:@"%lds",time];
                [sendButton setTitle:timeStr forState:UIControlStateNormal];
                sendButton.enabled = NO;
                if (time == 0) {
                    [sendButton setTitle:@"重新发送" forState:UIControlStateNormal];
                    sendButton.enabled = YES;
                }
            }];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

- (void)loadCapitalHdcSwapCalculation {
    if (![self.countField.text isNotBlank]) {
        self.xhgwzLabel.text = @"需消耗购物值：0.00";
        if (self.type == 2) {
            self.kdhLabel.text = @"可兑换：0.00冻结能量";
        } else {
            self.kdhLabel.text = @"可兑换：0.00现金余额";
        }
        return;
    }
    [HNSH_ExchangeNetServer requestCapitalHdcSwapCalculationWithAmount:self.countField.text type:self.type success:^(ST_BaseNetModel * _Nullable responseObject) {
        //obtain 可获得数量
        //poundage 手续费 有可能没有
        //expend_shopping_value 购物值支出
        if (responseObject.code == 0) {
            self.kdhLabel.text = [NSString stringWithFormat:@"可兑换：%@",responseObject.resultset[@"obtain"]];
            NSString *expend_shopping_value = [NSString stringWithFormat:@"%@",responseObject.resultset[@"expend_shopping_value"]];
            if ([expend_shopping_value isNotBlank]) {
                self.xhgwzLabel.text = [NSString stringWithFormat:@"需消耗购物值：%@",responseObject.resultset[@"expend_shopping_value"]];
            } else {
                self.xhgwzLabel.text = @"需消耗购物值：0.00";
            }
        }
        
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

@end
